// pages/myReimbursement/index.js
const app = getApp()

Page({

    /**
     * 页面的初始数据
     */
    data: {
        show: false,//控制下拉列表的显示隐藏，false隐藏、true显示
        ApprovalList: [],//流程审批列表
        name: '',
        tel: '',
        money: '',
        reviewTel: '',
        fan: '',
        door: '',
        tube: '',
        inversion: '',
        transfer: '',
        window: '',
        pack: '', // 打包类目
        brandId: '', // 品牌
        materialId: '', // 型号
        thicknessId: '', // 壁厚
        openId: '', // 开启
        type: '',
        asterisk: '',
        affiliated: '',
        createTime: '',
        updateTime: '',
        createTime1: '',
        updateTime1: '',
        currentTab: 0,
        pageNum: 1,
        pageSize: 50,
        total: 0,
        getTotal: 0,
        mines: 0,
        isPages: true,
        pageSizeIndex: 1,
        status: '',
        isDelivery: '',
        columns: [
            { value: 0, name: 10 },
            { value: 1, name: 50 },
            { value: 2, name: 100 },
            { value: 6, name: 300 },
            { value: 3, name: 500 },
            { value: 4, name: 1000 },
            { value: 5, name: 5000 },
        ],
        totalMoney: 0,
        isPlacement: '',
        searchTagList: [],
        allTotal: 0, // 总货款
        allCollection: 0, // 总收款
        allSurplus: 0, // 剩余款
        // allFan: 0,  // 开扇数量
        // allDoor: 0, // 开门数量
        // allTube: 0, // 方管数量
        // allInversion: 0, // 内倒数量
        // allTransfer: 0, // 转角数量
        // allWindow: 0, // 纱窗数量
        nowDate: '',
        allList: [],
        active: [5],
        admin: 0,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options, query) {
        wx.hideShareMenu()
    },


    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {
        this.workorderList = this.selectComponent("#workorderList")
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
        this.setData({
            pageNum: 1,
            pageSize: 50,
            pageSizeIndex: 1,
            currentTab: 0,
        });
        if (!wx.getStorageSync('userPhone')) return;
          this.childComponent = this.selectComponent("#moneySearch");
          this.childComponent.reset();
          this.getNum();
          this.getApprovalListData(0);
          this.getDate();
          this.setData({
            admin: wx.getStorageSync('admin') == 1 || wx.getStorageSync('subAdmin') == 1 ? 1 : 0
          })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {
        this.setData({
            pageNum: 1,
            pageSize: 50,
            pageSizeIndex: 1,
            currentTab: 0,
        });
        this.childComponent = this.selectComponent("#moneySearch");
        this.childComponent.reset();
        this.getNum();
        this.getApprovalListData(0);
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage(res) {

    },

    //  tab切换逻辑
    swichNav: function (e) {
        var that = this;
        if (this.data.currentTab === e.currentTarget.dataset.current) {
            return false;
        } else {
            that.setData({
                currentTab: e.currentTarget.dataset.current,
                pageSize: 50,
                pageSizeIndex: 3,
            })
            this.childComponent = this.selectComponent("#moneySearch");
            this.childComponent.reset();
        }
    },

    getNum: function () {
        wx.request({
            url: `${app.globalData.baseUrl}/api/finance/getTotal`,
            method: "GET",
            header: {
                'token': wx.getStorageSync('token'),
                "Content-Type": "application/json"
            },
            success: (res) => {
                if (res.data.code == 0) {
                    this.setData({
                        total: res.data.data.mine,
                        getTotal: res.data.data.total,
                        mines: res.data.data.mines
                    });
                }
            }
        })
    },

    // // TOO 财务工单的详情页面
    toDetail(e) {
        let id = e.currentTarget.dataset.id;
        // TOO  添加财务工单页面
        wx.navigateTo({
            url: `/pages/financialDetails/index?id=${id}&status=${this.data.currentTab}`
        })
    },

    // 获取我发的报销列表  传值搜索
    getApprovalListData(val) {
      if (!wx.getStorageSync('userPhone')) return;
        wx.showLoading({
            title: '加载中...',
        });
        const { active } = this.data;
        wx.request({
            url: `${app.globalData.baseUrl}${val == 0 ? '/api/finance/selList' : val == 1 ? '/api/finance/selMakeList' : '/api/finance/selMakeLists'}`,
            method: "GET",
            header: {
                'token': wx.getStorageSync('token'),
                "Content-Type": "application/json"
            },
            data: {
                name: this.data.name,
                tel: this.data.tel,
                reviewTel: this.data.reviewTel,
                fan: this.data.fan,
                door: this.data.door,
                tube: this.data.tube,
                inversion: this.data.inversion,
                transfer: this.data.transfer,
                window: this.data.window,
                pack: this.data.pack, // 打包类目
                brandId: this.data.brandId, // 品牌
                materialId: this.data.materialId, // 型号
                asterisk: this.data.asterisk,
                thicknessId: this.data.thicknessId, // 壁厚
                openId: this.data.openId, // 开启
                type: this.data.type,
                money: this.data.money,
                status: this.data.status,
                isDelivery: this.data.isDelivery,
                affiliated: this.data.affiliated,
                createTime: this.data.createTime ? this.data.createTime : '',
                updateTime: this.data.updateTime ? this.data.updateTime : '',
                createTime1: this.data.createTime1 ? this.data.createTime1 : '',
                updateTime1: this.data.updateTime1 ? this.data.updateTime1 : '',
                pageNum: this.data.pageNum,
                pageSize: this.data.pageSize,
                isPlacement: active.includes(0) ? 0 : active.includes(1) ? 1 : '',
                sign1: active.includes(2) ? 0 : active.includes(3) ? 1 : '',
            },
            success: (res) => {
                if (res.data.code != 0) return;
                let list = this.data.pageNum == 1 ? res.data.rows : this.quchong([...this.data.ApprovalList, ...res.data.rows]);
                const allList = JSON.parse(JSON.stringify(this.data.pageNum == 1 ? res.data.rows : this.quchong([...this.data.allList, ...res.data.rows])));
                let flag = true;
                if (allList.length >= res.data.total) {
                    flag = false;
                }
                let num = 0,
                allTotal = 0,
                allCollection =0,
                allSurplus = 0;
                // allFan = 0,
                // allDoor = 0,
                // allTube = 0, 
                // allInversion = 0, 
                // allTransfer = 0,
                // allWindow = 0;
                if (active.includes(4)) list = list.filter(item => (parseFloat(item.total || 0) + parseFloat(item.changeTotal || 0) - parseFloat(item.paid || 0)) > 0);
                list.forEach(item => {
                    num += parseFloat(item.money);
                    item.surplus = (parseFloat(item.total || 0) + parseFloat(item.changeTotal || 0) - parseFloat(item.paid || 0)).toFixed(2) || 0;
                    allTotal = allTotal + parseFloat(item.total) + parseFloat(item.changeTotal);
                    allCollection += parseFloat(item.paid);
                    allSurplus += parseFloat(item.surplus);
                    // allFan += parseFloat(item.fan*100);
                    // allDoor += parseFloat(item.door*100);
                    // allTube += parseFloat(item.tube*100);
                    // allInversion += parseFloat(item.inversion*100);
                    // allTransfer += parseFloat(item.transfer*100);
                    // allWindow += parseFloat(item.window*100);
                    item.totalShow = (parseFloat(item.total) + parseFloat(item.changeTotal)).toFixed(2);
                    item.isOpen = true;
                });
                this.setData({
                    allList,
                    ApprovalList: list,
                    isPages: flag,
                    totalMoney: num,
                    allTotal: allTotal.toFixed(2), // 总货款
                    allCollection: allCollection.toFixed(2), // 总收款
                    allSurplus: allSurplus.toFixed(2), // 剩余款
                    // allFan: allFan > 0 ? (allFan / 100).toFixed(2) : '',  // 开扇数量
                    // allDoor: allDoor > 0 ? (allDoor / 100).toFixed(2) : '', // 开门数量
                    // allTube: allTube > 0 ? (allTube / 100).toFixed(2) : '', // 方管数量
                    // allInversion: allInversion > 0 ? (allInversion / 100).toFixed(2) : '', // 内倒数量
                    // allTransfer: allTransfer > 0 ? (allTransfer / 100).toFixed(2) : '', // 转角数量
                    // allWindow: allWindow > 0 ? (allWindow / 100).toFixed(2) : '', // 纱窗数量
                });
                wx.hideLoading();
            }
        })
    },

    onReachBottom() {
        if (!this.data.isPages) return;
        var pages = this.data.pageNum;
        var page = pages + 1;
        this.setData({ pageNum: page });
        this.getApprovalListData(this.data.currentTab);
    },

    // 数据去重
    quchong(arr) {
        var tempArr = []; //返回的值
        var indexArr = []; //返回的索引
        for (var i = 0; i < arr.length; i++) {
            if (tempArr.indexOf(arr[i]) == -1) {
                tempArr.push(arr[i]);
                indexArr.push(i)
            } else if (tempArr.indexOf(arr[i]) >= 0) {
                for (var j = 0; j < tempArr.length; j++) {
                    if (tempArr[j] == arr[i]) {
                        tempArr.splice(j, 1, tempArr[j]);
                        indexArr.splice(j, 1, i);
                    }
                }
            }
        }
        return tempArr
    },

    onSelectPageSize(e) {
        this.setData({
            pageSizeIndex: e.detail.value,
            pageNum: 1,
            pageSize: this.data.columns[e.detail.value].name,
            isPages: true,
        });
        this.getApprovalListData(this.data.currentTab);
    },

    onDisplay() {
        this.setData({ show: true });
    },

    onClose() {
        this.setData({ show: false });
    },

    search(e) {
        const form = e.detail.form;
        const nameObj = e.detail.nameObj;
        this.setData({
            ...form,
            pageNum: 1,
            show: false,
        });
        this.getApprovalListData(this.data.currentTab);
        const arr = [];
        if(form.name) arr.push(`详细地址:${form.name}`);
        if(form.tel) arr.push(`联系电话:${form.tel}`);
        if(form.type) arr.push(`项目加工形态:${form.type}`);
        if(form.money) arr.push(`装修数量:${form.money}`);
        if(form.reviewTel) arr.push(`发起人和电话:${form.reviewTel}`);
        if(form.fan) arr.push(`开扇数量:${form.fan}`);
        if(form.door) arr.push(`开门数量:${form.door}`);
        if(form.tube) arr.push(`方管数量:${form.tube}`);
        if(form.inversion) arr.push(`内倒数量:${form.inversion}`);
        if(form.transfer) arr.push(`转角数量:${form.transfer}`);
        if(form.window) arr.push(`开扇纱窗数量:${form.window}`);
        if(nameObj.packName) arr.push(`打包类目:${nameObj.packName}`);
        if(nameObj.brandName) arr.push(`品牌:${nameObj.brandName}`);
        if(nameObj.materialName) arr.push(`型号:${nameObj.materialName}`);
        if(nameObj.thicknessName) arr.push(`壁厚:${nameObj.thicknessName}`);
        if(nameObj.openName) arr.push(`开启:${nameObj.openName}`);
        if(nameObj.typeName) arr.push(`部门:${nameObj.typeName}`);
        if(nameObj.deliveryName) arr.push(`是否交付:${nameObj.deliveryName}`);
        if (nameObj.affiliatName) arr.push(`隶属归类：${nameObj.affiliatName}`)
        if (form.createTime1) arr.push(`创建时间:${form.createTime1} - ${form.updateTime1}`);
        if (form.createTime) arr.push(`更新时间:${form.createTime} - ${form.updateTime}`);
        if (nameObj.asteriskName) arr.push(`星星状态：${nameObj.asteriskName}`);
        this.setData({ searchTagList: arr });
    },

    resetIsPage() {
        this.setData({ isPages: true });
    },

    clearSearch() {
        this.setData({ searchTagList: [] });
        this.childComponent = this.selectComponent("#moneySearch");
        this.childComponent.reset();
    },

    isPlacementChange(e) {
        let { active } = this.data;
        if(e.currentTarget.dataset.id === 0) {
            if(active.includes(0)) {active = active.filter(item => item !== 0 && item !== 1 && item !== 5);console.log(active);}
            else {active = active.filter(item => item !== 1 && item !== 5); active.push(0);}
            this.setData({ active });
        }else if(e.currentTarget.dataset.id === 1) {
            if(active.includes(1)) {active = active.filter(item => item !== 0 && item !== 1 && item !== 5);}
            else {active = active.filter(item => item !== 0 && item !== 5); active.push(1);}
            this.setData({ active });
        }else if(e.currentTarget.dataset.id === 2) {
            if(active.includes(2)) {active = active.filter(item => item !== 2 && item !== 3 && item !== 5);}
            else {active = active.filter(item => item !== 3 && item !== 5); active.push(2);}
            this.setData({ active });
        }else if(e.currentTarget.dataset.id === 3) {
            if(active.includes(3)) {active = active.filter(item => item !== 2 && item !== 3 && item !== 5);}
            else {active = active.filter(item => item !== 2 && item !== 5); active.push(3);}
            this.setData({ active });
        }else if(e.currentTarget.dataset.id === 4) {
            if(active.includes(4)) {active = active.filter(item => item !== 4 && item != 5);}
            else {active.push(4);}
            this.setData({ active });
        }
        if(e.currentTarget.dataset.id === 5 || this.data.active.length === 0) {
            this.setData({ active: [5] });
        }
        this.setData({ pageNum: 1, pageSize: 50, pageSizeIndex: 1 });
        this.getApprovalListData(this.data.currentTab);
    },

    panel(e) {
        const arr = this.data.ApprovalList;
        arr.forEach(item => {
            if(e.currentTarget.dataset.id == item.id) item.isOpen = !item.isOpen;
        });
        this.setData({ ApprovalList: arr })
    },

    getDate() {
        let date = new Date();
        // 获取年份
        let year = date.getFullYear();
        // 获取月份，注意月份是从0开始的，所以需要加1
        let month = date.getMonth() + 1;
        // 获取日期
        let day = date.getDate();
        // 格式化月份、日期、分钟和秒数，如果小于10则在前面补0
        month = month < 10 ? '0' + month : month;
        day = day < 10 ? '0' + day : day;

        // 组合成需要的格式
        const formattedDate = `${year}-${month}-${day}`;
        this.setData({ nowDate: formattedDate });
    }
})